const { OrderModel, UserModel } = require('../../models/index')
const { Op } = require('sequelize')

// 获取订单列表信息
const getOrderList = async (req, res) => {
  try {
    // 从分页中间件中获取分页信息
    const { offset, pageSize } = req.pagination;

    const orderlList = await OrderModel.findAndCountAll({
      attributes: ['order_id', 'order_type', 'place_name', 'product_type', 'price', 'quantity', 'total_amount', 'travel_start_date', 'travel_end_date', 'people', 'status', 'createdAt'],
      include: [
        {
          model: UserModel,
          as: 'order_user',
          attributes: ['username', 'phone', 'avatar']
        }
      ],
      order: [
        ['updatedAt', 'DESC'],
        ['createdAt', 'DESC']
      ],
      offset: offset,
      limit: parseInt(pageSize, 10)
    })

    res.status(200).json({
      title: '订单列表信息',
      data: orderlList
    })

  } catch (error) {
    res.status(500).json({ error: error.message })
  }
}

// 订单列表搜索功能
const searchOrder = async (req, res) => {
  try {
    // 获取用户输入的搜索词
    const searchText = req.query.data

    // 如果搜索词为空返回空数组
    if (!searchText || searchText.trim() === '') {
      return res.status(200).json([])
    }

    // 搜索匹配内容
    const orderItem = await OrderModel.findAll({
      include: [
        {
          model: UserModel,
          as: 'order_user',
          attributes: ['username', 'phone', 'avatar']
        }
      ],
      where: {
        [Op.or]: [
          { place_name: { [Op.like]: `%${searchText}%` } },
          { product_type: { [Op.like]: `%${searchText}%` } },
          { price: { [Op.like]: `%${searchText}%` } },
          { quantity: { [Op.like]: `%${searchText}%` } },
          { total_amount: { [Op.like]: `%${searchText}%` } },
          { travel_start_date: { [Op.like]: `%${searchText}%` } },
          { travel_end_date: { [Op.like]: `%${searchText}%` } },
          { '$order_user.username$': { [Op.like]: `%${searchText}%` } },
          { '$order_user.phone$': { [Op.like]: `%${searchText}%` } },
        ]
      }
    })

    // 返回查询结果
    return res.status(200).json({
      title: '搜索成功',
      data: orderItem
    })
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
}

module.exports = {
  getOrderList,
  searchOrder
}